package com.logisticsrepair.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.logisticsrepair.entity.WorkerProfileExtendEntity;
import com.logisticsrepair.service.WorkerProfileService;
import com.logisticsrepair.util.responseUtil.ResponseEnum;
import com.logisticsrepair.util.responseUtil.ResponseUtil;
import com.logisticsrepair.util.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 维修工个人中心控制器
 */
@RestController
@RequestMapping("/workerProfile")
public class WorkerProfileController {

    @Autowired
    private WorkerProfileService workerProfileService;

    /**
     * 获取当前维修工个人资料
     */
    @GetMapping("/getWorkerProfile")
    public ResponseUtil getWorkerProfile() {
        String openid = StpUtil.getLoginId().toString();
        WorkerProfileExtendEntity profile = workerProfileService.getProfileByOpenId(openid);
        
        // 如果没有找到个人资料，则初始化
        if (profile == null) {
            boolean initSuccess = workerProfileService.initProfile(openid);
            if (initSuccess) {
                profile = workerProfileService.getProfileByOpenId(openid);
            } else {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("获取个人资料失败");
            }
        }
        
        // 解析JSON数据
        if (profile.getSpecializations() != null) {
            try {
                profile.setSpecializations(profile.getSpecializations());
            } catch (Exception ignored) {}
        }
        
        if (profile.getCertifications() != null) {
            try {
                profile.setCertifications(profile.getCertifications());
            } catch (Exception ignored) {}
        }
        
        return ResponseUtil.setE(ResponseEnum.OK).setData(profile);
    }

    /**
     * 更新维修工个人资料 - 处理JSON数据
     */
    @PostMapping(value = "/updateProfile", consumes = "application/json")
    public ResponseUtil updateProfileJson(@RequestBody WorkerProfileExtendEntity profile) {
        return processProfileUpdate(profile);
    }
    
    /**
     * 更新维修工个人资料 - 处理表单数据
     */
    @PostMapping(value = "/updateProfile", consumes = "multipart/form-data")
    public ResponseUtil updateProfileForm(WorkerProfileExtendEntity profile) {
        return processProfileUpdate(profile);
    }
    
    /**
     * 处理个人资料更新的通用方法
     */
    private ResponseUtil processProfileUpdate(WorkerProfileExtendEntity profile) {
        try {
            String openid = profile.getOpenid();
            if (openid == null || openid.isEmpty()) {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("维修工ID不能为空");
            }
            
            // 设置更新时间
            profile.setUpdateTime(new Date());
            
            // 如果birthday为null，不做任何处理
            // 如果birthday不为null，后端会自动处理日期格式
            
            System.out.println("接收到的维修工个人资料数据: " + profile);
            
            boolean success = workerProfileService.updateProfile(profile);
            if (success) {
                return ResponseUtil.setE(ResponseEnum.OK).setMsg("个人资料更新成功");
            } else {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("个人资料更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("个人资料更新失败: " + e.getMessage());
        }
    }

    /**
     * 上传头像
     */
    @PostMapping("/uploadAvatar")
    public ResponseUtil uploadAvatar(@RequestParam("file") MultipartFile file) {
        String openid = StpUtil.getLoginId().toString();
        
        if (file.isEmpty()) {
            return ResponseUtil.setE(ResponseEnum.PARAMS_ERROR).setMsg("上传文件为空");
        }
        
        try {
            // 保存头像文件
            File savedFile = Public.saveUserPhoto(file, openid, "avatar");
            String absolutePath = savedFile.getAbsolutePath();
            String path = absolutePath.substring(absolutePath.indexOf("static") + 6);
            
            // 更新头像路径
            WorkerProfileExtendEntity profile = workerProfileService.getProfileByOpenId(openid);
            if (profile == null) {
                workerProfileService.initProfile(openid);
                profile = workerProfileService.getProfileByOpenId(openid);
            }
            
            profile.setAvatar(path);
            workerProfileService.updateById(profile);
            
            return ResponseUtil.setE(ResponseEnum.OK)
                .setMsg("头像上传成功")
                .setData(profile.getAvatar());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("头像上传失败");
        }
    }
    
    /**
     * 获取技能等级信息
     */
    @GetMapping("/getSkillLevelInfo")
    public ResponseUtil getSkillLevelInfo() {
        return ResponseUtil.setE(ResponseEnum.OK).setData(workerProfileService.getSkillLevelInfo());
    }
    
    /**
     * 获取可选专长领域
     */
    @GetMapping("/getSpecializations")
    public ResponseUtil getSpecializations() {
        List<Map<String, Object>> specializations = new ArrayList<>();
        
        Map<String, Object> spec1 = new HashMap<>();
        spec1.put("id", "electrical");
        spec1.put("name", "电气维修");
        
        Map<String, Object> spec2 = new HashMap<>();
        spec2.put("id", "plumbing");
        spec2.put("name", "水暖维修");
        
        Map<String, Object> spec3 = new HashMap<>();
        spec3.put("id", "carpentry");
        spec3.put("name", "木工维修");
        
        Map<String, Object> spec4 = new HashMap<>();
        spec4.put("id", "electronics");
        spec4.put("name", "电子设备维修");
        
        Map<String, Object> spec5 = new HashMap<>();
        spec5.put("id", "hvac");
        spec5.put("name", "暖通空调维修");
        
        specializations.add(spec1);
        specializations.add(spec2);
        specializations.add(spec3);
        specializations.add(spec4);
        specializations.add(spec5);
        
        return ResponseUtil.setE(ResponseEnum.OK).setData(specializations);
    }

    /**
     * 通过openid直接获取维修工个人资料
     * 此方法仅供前端调试使用，生产环境应该移除
     */
    @GetMapping("/directGetProfile")
    public ResponseUtil directGetProfile(@RequestParam String openid) {
        WorkerProfileExtendEntity profile = workerProfileService.getProfileByOpenId(openid);
        
        // 如果没有找到个人资料，则初始化
        if (profile == null) {
            boolean initSuccess = workerProfileService.initProfile(openid);
            if (initSuccess) {
                profile = workerProfileService.getProfileByOpenId(openid);
            } else {
                return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("获取个人资料失败");
            }
        }
        
        // 解析JSON数据
        if (profile.getSpecializations() != null) {
            try {
                profile.setSpecializations(profile.getSpecializations());
            } catch (Exception ignored) {}
        }
        
        if (profile.getCertifications() != null) {
            try {
                profile.setCertifications(profile.getCertifications());
            } catch (Exception ignored) {}
        }
        
        return ResponseUtil.setE(ResponseEnum.OK).setData(profile);
    }
} 